//数据源数组
let dataSourceFetchPromises = [];
//摘要数据数组
let dataSummaryFetchPromises = [];
//底层数据数组
let dataUnderlyingFetchPromises = [];
//数据源对象
let dashboardDataSources = {};
//摘要数据对象
let dashboardSummaryData = {};
//底层数据对象
let dashboardUnderlyingData = {};
let dashboard;
//工作表视图数组
let worksheetsArry=[];
//工作表视图对象
let workSheets={};
let oldTest=[];
let oldTestStr="";

let test=[];
let testStr = "";
//判断是否绑定
let buidFlag = false;
//传给配置框的参数
let configCs = {};
//偏移值
let pyz = 0;
//显示top的数目
let topNums = 5;
//一行显示几个
let hangNums = 5;
//上下边距
let pdtb = 10;
//左边距
let pdz = 10;
//右边距
let pdy = 10;
//每个图片的宽
let ItemWidth = 20 - pyz;
//每个图片的高
let ItemHeight = 20 - pyz;
//所有行的高度
let imageFitemH = 20;
//背景颜色
let bjys = '#ffffff';
//平分窗口高度
let mytpgd = false;
//目标工作表（若多个用英文,隔开）
let mbgzb='';
//图片圆角（px/百分比）
let tpyj = '';
//目标图片字段
let mbgzzd = 'Post thumbnail URL';

//目标字段
let targetField="Post thumbnail URL";

//默认图片
let bjtpUrl = "../images/null_pic.png";

(function(){

    $(document).ready(function () {

        debugger;
        tableau.extensions.initializeAsync({'configure':configure}).then(function () {
            dashboard = tableau.extensions.dashboardContent.dashboard;

            ConfigurationPar();

            var init = function(){
                dashboard.worksheets.forEach(function (worksheet) {
                    //获取数据源
                    // dataSourceFetchPromises.push(worksheet.getDataSourcesAsync());

                    if(mbgzb){
                        //扫描目标工作表
                        if(worksheet.name==mbgzb || mbgzb.indexOf(worksheet.name+',') != -1 || mbgzb.indexOf(','+worksheet.name+',') != -1 || mbgzb.indexOf(','+worksheet.name) != -1){
                            //获取摘要数据
                            dataSummaryFetchPromises.push(worksheet.getSummaryDataAsync());
                            //获取底层数据
                            // dataUnderlyingFetchPromises.push(worksheet.getUnderlyingDataAsync());
                            worksheetsArry.push(worksheet);
                            workSheets[worksheet.name]=worksheet;
                        }
                    }else{//扫描所有工作表
                      //获取摘要数据
                      dataSummaryFetchPromises.push(worksheet.getSummaryDataAsync());
                      //获取底层数据
                      // dataUnderlyingFetchPromises.push(worksheet.getUnderlyingDataAsync());
                      worksheetsArry.push(worksheet);
                      workSheets[worksheet.name]=worksheet;
                    }


                });

                // Promise.all([dataSourceFetchPromises,dataSummaryFetchPromises,dataUnderlyingFetchPromises]).then(function (fetchResultsArr) {
                //     debugger;
                //     //数据源对象
                //     fetchResultsArr[0].forEach(function (dataSourcesForWorksheet) {
                //         dataSourcesForWorksheet.forEach(function (dataSource) {
                //             if (!dashboardDataSources[dataSource.id]) { // We've already seen it, skip it.
                //                 dashboardDataSources[dataSource.id] = dataSource;
                //             }
                //         });
                //     });
                //     //摘要数据对象
                //     fetchResultsArr[1].forEach(function (dataSummaryForWorksheet) {
                //         dataSummaryForWorksheet.forEach(function (dataSummary) {
                //             if (!dashboardSummaryData[dataSource.id]) { // We've already seen it, skip it.
                //                 dashboardSummaryData[dataSource.id] = dataSummary;
                //             }
                //         });
                //     });
                //     //底层数据对象
                //     fetchResultsArr[2].forEach(function (dataUnderlyingForWorksheet) {
                //         dataUnderlyingForWorksheet.forEach(function (dataUnderlying) {
                //             if (!dashboardUnderlyingData[dataSource.id]) { // We've already seen it, skip it.
                //                 dashboardUnderlyingData[dataSource.id] = dataUnderlying;
                //             }
                //         });
                //     });
                //     debugger;
                // },function(error){
                //     console.log("异步失败！！！" + error);
                //     console.log(JSON.stringify(error));
                // });
      
                Promise.all(dataSummaryFetchPromises.map(p => p.catch(e => e))).then(function (fetchResultsArrS) {
                  console.log("fetchResultsArrS: "+fetchResultsArrS);
                    debugger;
                    //摘要数据对象
                    // fetchResultsArrS.forEach(function (dataSummary) {
                    //             if (!dashboardSummaryData[dataSummary.name]) { // We've already seen it, skip it.
                    //                 dashboardSummaryData[dataSummary.name] = dataSummary;
                    //             }
                    //     });
                    //去重器
                    // let qc = {};
                    //遍历每个worksheet的摘要数据
                    for (let i = 0; i < fetchResultsArrS.length; i++) {
                        // dashboardSummaryData[worksheetsArry[i]["name"]] = fetchResultsArrS[i];
                        if(fetchResultsArrS[i].columns){
                            //遍历摘要数据的列名
                            for (let j = 0; j < fetchResultsArrS[i].columns.length; j++) {
                                //取出目标列名的数据
                                if (fetchResultsArrS[i].columns[j].fieldName == targetField && fetchResultsArrS[i].data){
                                    for (let k = 0; k < fetchResultsArrS[i].data.length; k++) {
                                        // if(fetchResultsArrS[i].data[k][j]["formattedValue"] && !qc[fetchResultsArrS[i].data[k][j]["formattedValue"]]){
                                            let obj = {};
                                            obj["worksheetName"] = worksheetsArry[i]["name"];
                                            obj["targetField"] =targetField;
                                            obj["value"] = fetchResultsArrS[i].data[k][j]["formattedValue"];
                                            test.push(obj);
                                            // qc[fetchResultsArrS[i].data[k][j]["formattedValue"]]=true;
                                        // }
                                    }
                                }
                            }
                        }
                    }

                    showImage(1);
                    //绑定监听事件
                    if(!buidFlag){
                        let wsp=[];
                        //去重器
                        let namespace = {};
                        for (let i = 0; i < test.length; i++) {

                            if(!namespace[test[i]["worksheetName"]]){

                                workSheets[test[i]["worksheetName"]].addEventListener(tableau.TableauEventType.FilterChanged,function(aa){
                                    debugger
                                        if(!flag){
                                            fcf();
                                            resetCS();
                                            init();
                                        }

                                });
                                workSheets[test[i]["worksheetName"]].addEventListener(tableau.TableauEventType.MarkSelectionChanged,function(aa){
                                    debugger
                                     if(!flag){
                                            fcf();
                                            resetCS();
                                            init();
                                        }

                                });
                                wsp.push(workSheets[test[i]["worksheetName"]].getParametersAsync());
                            }
                            namespace[test[i]["worksheetName"]] = true;
                        }

                        //绑定参数改变监听
                        Promise.all(wsp).then(function(see){
                            see.forEach(function (p) {
                                p.forEach(function(pp){
                                    pp.addEventListener(tableau.TableauEventType.ParameterChanged, function (aa) {
                                        if(!flag){
                                            fcf();
                                            resetCS();
                                            init();
                                        }
                                    });
                                });
                            });
                        },function(err){
                            console.log(err)
                        });
                    }
                    buidFlag = true;
                },function(error){
                    console.log("摘要异步失败！！！" + error);
                    console.log(JSON.stringify(error));
                });
            };
            init();

        }, function (err) {
            // Something went wrong in initialization.
            console.log('Error while Initializing: ' + err.toString());
        });
    });
})();
function aaa() {
 alert("a");
}

//防重复标示
var flag = false;
//防重复函数
function fcf(){
    flag = true;
    setTimeout(function () {
       flag = false;
    },500)
}

//重制参数
function resetCS(){
//数据源数组
     dataSourceFetchPromises = [];
//摘要数据数组
     dataSummaryFetchPromises = [];
//底层数据数组
     dataUnderlyingFetchPromises = [];
//数据源对象
     dashboardDataSources = {};
//摘要数据对象
     dashboardSummaryData = {};
//底层数据对象
     dashboardUnderlyingData = {};
     dashboard;
//工作表视图数组
     worksheetsArry=[];
//工作表视图对象
     workSheets={};
     test=[];
}



function showImage(num) {
    debugger;
    let cout = 0;
    if(num==1&&oldTest.length == 0){
      console.log("初始化oldTest");
      oldTest = test;
      num = 0;
    }

      setTimeout(function () {
             if((num ==0 && test.length > 0) || !equalsObj(oldTest,test) ){
                         console.log("刷新图片");
                         oldTest = test;
                         //清空元素
                         // $(".imagesItem").css("background-image","url("+location.href.substring(0,location.href.indexOf("showimage"))+"/images/null_pic.png)");
                         $(".imageFitem").html("");
                         // $(".imagesItem").text("");
                         let str = "";
                         //匹配视频格式正则
                         let reg = /.*\.(mp4|avi|rm|rmvb|mkv|wkv)/i;

                         let heightUnit = "vw";

                         if (mytpgd){
                             heightUnit = "%";
                         }

                         //生成top
                         for (let i = 0; i < topNums; i++) {
                             if (test[i]&&test[i]["value"]){
                                 $("#image"+cout).css("background-image","url("+test[i]["value"]+")");

                                 if (reg.test(test[i]["value"])){//视频
                                     str += "<video  src=\""+test[i]["value"]+"\" class=\"imagesItem\" preload=\"meta\" style=\"width: "+ItemWidth+"%;height: "+ItemHeight+heightUnit+";background-image: none;\"></video>"
                                 }else{//图片
                                     str += "<div  class=\"imagesItem\" style=\"background-image:url("+test[i]["value"]+");width: "+ItemWidth+"%;height: "+ItemHeight+heightUnit+";\"></div>"
                                 }

                             }else{//显示默认图片
                                 str += "<div  class=\"imagesItem\" style='width: "+ItemWidth+"%;height: "+ItemHeight+heightUnit+";background-image: url("+bjtpUrl+");'></div>"
                             }
                             cout++;
                         }
                         $(".imageFitem").html(str);
                         $('body').css('background-color',bjys);
                         if(bjys.indexOf("gradient") != -1){
                             $('body').css('background-color','transparent');
                             $('body').css('background-image',bjys);
                         }

                         //设置边距
                         $(".imagesItem").css("padding",pdtb+"px "+pdy+ "px "+pdtb+"px "+pdz+"px");
                         $(".imageFitem").height(imageFitemH+"vw");

                         if(tpyj){//图片圆角
                             $(".imagesItem").css("border-radius",tpyj);
                         }else {
                             $(".imagesItem").css("border-radius","0");
                         }

                         if (mytpgd){
                             $(".imageFitem").height("100%");
                         }
             }else if(num ==0 && test.length == 0){
                  console.log("使用默认图片");
                  $(".imagesItem").css("background-image","url("+bjtpUrl+")");
             }
        },100);
}

//设置界面
function configure() {

    // const popupUrl = window.location.origin+'/xsj/setting';
    const popupUrl = 'https://vinsonzeng.gitee.io/nweworlddemo/templates/setting';
    var obj =  tableau.extensions.settings.getAll()["ImagePra"]?JSON.parse(tableau.extensions.settings.getAll()["ImagePra"]):{};
//    debugger;
    configCs["pdtb"]=(obj["pdtb"]?obj["pdtb"]:10);
    configCs["pdz"]=(obj["pdz"]?obj["pdz"]:10);
    configCs["pdy"]=(obj["pdy"]?obj["pdy"]:10);
    configCs["hangNums"] =  (obj["hangNums"]?obj["hangNums"]:5);
    configCs["topNums"] =  (obj["topNums"]?obj["topNums"]:5);
    configCs["bjys"] =  (obj["bjys"]?obj["bjys"]:'#ffffff');
    configCs["mbgzb"] =  (obj["mbgzb"]?obj["mbgzb"]:'');
    configCs["tpyj"] =  (obj["tpyj"]?obj["tpyj"]:'');
    configCs["mbgzzd"] =  (obj["mbgzzd"]?obj["mbgzzd"]:'Post thumbnail URL');
    configCs["tpgd"] =  (obj["tpgd"]!=null?obj["tpgd"]:'0');
    configCs["bjtpUrl"] =  (obj["bjtpUrl"]!=null?obj["bjtpUrl"]:'');
    tableau.extensions.ui.displayDialogAsync(popupUrl, JSON.stringify(configCs), { height: 700, width: 700 }).then((closePayload) => {
     // var obj2 = JSON.parse(closePayload);
     // $(".imagesItem").css("padding",obj2["pdtb"]+"px "+obj2["pdzy"] + "px");
     //    location.replace(location);
        ConfigurationPar();
        showImage(0);
    }).catch((error) => {
        // One expected error condition is when the popup is closed by the user (meaning the user
        // clicks the 'X' in the top right of the dialog).  This can be checked for like so:
        switch (error.errorCode) {
            case tableau.ErrorCodes.DialogClosedByUser:
                console.log('Dialog was closed by user');
                break;
            default:
                console.error(error.message);
        }
    });
}

//配置参数
function ConfigurationPar() {
    debugger;
    let aaa = tableau.extensions.settings.getAll();
    if(aaa["ImagePra"]){
        let bbb = JSON.parse(aaa["ImagePra"]);
        console.log(bbb)
        pdtb = bbb["pdtb"];
        pdz = bbb["pdz"];
        pdy = bbb["pdy"];
        topNums = +bbb["topNums"];
        hangNums = +bbb["hangNums"];
        bjys = bbb["bjys"];
        tpyj = bbb["tpyj"];
        mbgzb = bbb["mbgzb"];
        mbgzzd = bbb["mbgzzd"];
        bjtpUrl = bbb["bjtpUrl"];

        if(mbgzzd){//目标字段
            targetField = mbgzzd;
        }

        //一行中每个元素的宽度(算出百分比-偏移值)
        ItemWidth = (100/hangNums) - pyz;
        ItemHeight = ItemWidth;

        //一共有几行
        let hang = 1;
        if(topNums > hangNums){
            hang = Math.ceil(topNums/hangNums);
        }
        imageFitemH = ItemHeight * hang;
        mytpgd = false;

        if (bbb["tpgd"]=="1"){//平分窗口高度
            mytpgd = true;
            ItemHeight = 100/hang;
        }
    }
}

/*
//计算显示的属性
function JSCK(){
    //一行中每个元素的宽度
    ItemWidth = 100/hangNums;
    ItemHeight = ItemWidth;

    //一共有几行
    let hang = topNums > hangNums?Math.ceil(topNums/hangNums):1;
    imageFitemH = ItemHeight * hang;

}*/

　　　　　　　　/**
             * 判断此对象是否是Object类型
             * @param {Object} obj
             */
            function  isObject(obj){
                return Object.prototype.toString.call(obj)==='[object Object]';
            };
            /**
             * 判断此类型是否是Array类型
             * @param {Array} arr
             */
            function isArray(arr){
                return Object.prototype.toString.call(arr)==='[object Array]';
            };
            /**
             *  深度比较两个对象是否相同
             * @param {Object} oldData
             * @param {Object} newData
             */
            function equalsObj(oldData,newData){
                // 类型为基本类型时,如果相同,则返回true
                if(oldData === newData) return true;
                if(isObject(oldData)&&isObject(newData)&&Object.keys(oldData).length === Object.keys(newData).length){
                    // 类型为对象并且元素个数相同

                    // 遍历所有对象中所有属性,判断元素是否相同
                    for (const key in oldData) {
                        if (oldData.hasOwnProperty(key)) {
                            if(!equalsObj(oldData[key],newData[key])){
                                // 对象中具有不相同属性 返回false
                                console.log(" 对象中具有不相同属性 返回false");
                                return false;
                            }
                        }
                    }
                }else if(isArray(oldData)&&isArray(oldData)&&oldData.length===newData.length){
                    // 类型为数组并且数组长度相同

                    for (let i = 0,length=oldData.length; i <length; i++) {
                        if(!equalsObj(oldData[i],newData[i])){
                            // 如果数组元素中具有不相同元素,返回false
                            console.log("如果数组元素中具有不相同元素,返回false");
                            return false;
                        }
                    }
                }else{
                    // 其它类型,均返回false
                    console.log("其它类型,均返回false");
                    return false;
                }

                // 走到这里,说明数组或者对象中所有元素都相同,返回true
                return true;
            };